package yicheng.dinnertogetherapp;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.widget.Toast;

public class UserInfoUpdateService extends Service{

	BroadcastReceiver broadcastReceiver;

	public static AmazonClientManager clientManager;

	static SharedPreferences local_user_information;
	SharedPreferences.Editor local_user_editor;
	String PREFS_NAME = "LocalUserInfo";

	String PHONE_NUMBER, NICKNAME;

	String START_TIME;
	String END_TIME;
	Date FROM_DATE;
	Date UNTIL_DATE;
	String ONLINE;
	/*
	private String PRIMARY_PHONE_NUMBER;
	private String PRIMARY_NICKNAME;*/


	private Handler handler;

	private void updateFromDateDisplay(){


		Calendar currentCal = Calendar.getInstance();

		int curYear = currentCal.get(Calendar.YEAR);
		int curMonth = currentCal.get(Calendar.MONTH);
		int curDay = currentCal.get(Calendar.DAY_OF_MONTH);
		int curHour = currentCal.get(Calendar.HOUR_OF_DAY);
		int curMin = currentCal.get(Calendar.MINUTE);

		Date currentDate = new Date(curYear, curMonth, curDay , curHour , curMin);

		String fromYear = local_user_information.getString("start_year", "0000");
		String fromMonth = local_user_information.getString("start_month", "00");
		String fromDay = local_user_information.getString("start_day", "00");
		String fromHour = local_user_information.getString("start_hour", "00");
		String fromMin = local_user_information.getString("start_min", "00");


		FROM_DATE = new Date(Integer.parseInt(fromYear), Integer.parseInt(fromMonth), Integer.parseInt(fromDay), Integer.parseInt(fromHour), Integer.parseInt(fromMin));


		String untilYear = local_user_information.getString("end_year", "0000");
		String untilMonth = local_user_information.getString("end_month", "00");
		String untilDay = local_user_information.getString("end_day", "00");
		String untilHour = local_user_information.getString("end_hour", "00");
		String untilMin = local_user_information.getString("end_min", "00");


		UNTIL_DATE = new Date(Integer.parseInt(untilYear), Integer.parseInt(untilMonth), Integer.parseInt(untilDay), Integer.parseInt(untilHour), Integer.parseInt(untilMin));


		SimpleDateFormat dateFormat = new SimpleDateFormat("yy/MM/dd h:mm a");
		SimpleDateFormat dayOfWeekFormat = new SimpleDateFormat("EE");
		Date dayOfWeekDate = new Date(curYear, curMonth, curDay - 1);

		String dayOfWeekText = dayOfWeekFormat.format(dayOfWeekDate);


		String current_time = dateFormat.format(currentDate);





		if (FROM_DATE.before(currentDate)){

			//from_date_textView.setText(dayOfWeekText + ", " + START_TIME);
			//START_TIME = dateFormat.format(FROM_DATE);
			START_TIME = dayOfWeekText + ", " + current_time;
			if (MyInfoActivity.from_date_textView != null){
				MyInfoActivity.from_date_textView.setText(START_TIME);

			}


			local_user_editor = local_user_information.edit();
			local_user_editor.putString("start_year", String.valueOf(curYear));
			local_user_editor.putString("start_month", String.valueOf(curMonth));
			local_user_editor.putString("start_day", String.valueOf(curDay));
			local_user_editor.putString("start_hour", String.valueOf(curHour));
			local_user_editor.putString("start_min", String.valueOf(curMin));
			local_user_editor.putString("start_time", START_TIME);
			local_user_editor.commit();

			//FROM_DATE= new Date(curYear, curMonth, curDay , curHour, curMin);
			updateStartTime();


		}
		else{

			START_TIME = local_user_information.getString("start_time", dayOfWeekText + ", " + current_time);
			if (MyInfoActivity.from_date_textView != null){
				MyInfoActivity.from_date_textView.setText(START_TIME);
			}

		}


		if (UNTIL_DATE.before(currentDate)){
			//until_date_textView.setText(dayOfWeekText + ", " + START_TIME);

			END_TIME = dayOfWeekText + ", " + current_time;
			if (MyInfoActivity.until_date_textView != null){
				MyInfoActivity.until_date_textView.setText(END_TIME);

			}

			local_user_editor = local_user_information.edit();
			local_user_editor.putString("end_year", String.valueOf(curYear));
			local_user_editor.putString("end_month", String.valueOf(curMonth));
			local_user_editor.putString("end_day", String.valueOf(curDay));
			local_user_editor.putString("end_hour", String.valueOf(curHour));
			local_user_editor.putString("end_min", String.valueOf(curMin));
			local_user_editor.putString("end_time", END_TIME);
			local_user_editor.commit();

			//UNTIL_DATE = new Date(curYear, curMonth, curDay , curHour, curMin);

			updateEndTime();





		}
		else{
			END_TIME = local_user_information.getString("end_time", dayOfWeekText + ", " + current_time);
			if (MyInfoActivity.until_date_textView != null){
				MyInfoActivity.until_date_textView.setText(END_TIME);
			}
		}



	}



	@Override
	public void onCreate() {
		// TODO Auto-generated method stub
		Toast.makeText(this , "service test create", Toast.LENGTH_SHORT).show();
		handler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				if (msg.what == 1){
					if (MyInfoActivity.make_me_available_switch != null){
						MyInfoActivity.make_me_available_switch.setEnabled(true);
					}

				}

			}
		};

		super.onCreate();
	}


	private void updateOnlineStatus(){
		Calendar currentCal = Calendar.getInstance();

		int curYear = currentCal.get(Calendar.YEAR);
		int curMonth = currentCal.get(Calendar.MONTH);
		int curDay = currentCal.get(Calendar.DAY_OF_MONTH);
		int curHour = currentCal.get(Calendar.HOUR_OF_DAY);
		int curMin = currentCal.get(Calendar.MINUTE);

		Date currentDate = new Date(curYear, curMonth, curDay , curHour , curMin);

		String untilYear = local_user_information.getString("end_year", "0000");
		String untilMonth = local_user_information.getString("end_month", "00");
		String untilDay = local_user_information.getString("end_day", "00");
		String untilHour = local_user_information.getString("end_hour", "00");
		String untilMin = local_user_information.getString("end_min", "00");


		UNTIL_DATE = new Date(Integer.parseInt(untilYear), Integer.parseInt(untilMonth), Integer.parseInt(untilDay), Integer.parseInt(untilHour), Integer.parseInt(untilMin));


		SimpleDateFormat dateFormat = new SimpleDateFormat("yy/MM/dd h:mm a");
		SimpleDateFormat dayOfWeekFormat = new SimpleDateFormat("EE");
		Date dayOfWeekDate = new Date(curYear, curMonth, curDay - 1);

		String dayOfWeekText = dayOfWeekFormat.format(dayOfWeekDate);


		String current_time = dateFormat.format(currentDate);

		if (UNTIL_DATE.before(currentDate)){
			//until_date_textView.setText(dayOfWeekText + ", " + START_TIME);

			/*	END_TIME = dayOfWeekText + ", " + current_time;
			if (MyInfoActivity.until_date_textView != null){
				MyInfoActivity.until_date_textView.setText(END_TIME);

			}

			local_user_editor = local_user_information.edit();
			local_user_editor.putString("end_year", String.valueOf(curYear));
			local_user_editor.putString("end_month", String.valueOf(curMonth));
			local_user_editor.putString("end_day", String.valueOf(curDay));
			local_user_editor.putString("end_hour", String.valueOf(curHour));
			local_user_editor.putString("end_min", String.valueOf(curMin));
			local_user_editor.putString("end_time", END_TIME);
			local_user_editor.commit();

			//UNTIL_DATE = new Date(curYear, curMonth, curDay , curHour, curMin);

			updateEndTime();*/

			updateDataBaseForOnlineStatus(false);



		}
		else{
			/*END_TIME = local_user_information.getString("end_time", dayOfWeekText + ", " + current_time);
			if (MyInfoActivity.until_date_textView != null){
				MyInfoActivity.until_date_textView.setText(END_TIME);
			}*/

			Toast.makeText(getBaseContext(), "not closing", Toast.LENGTH_LONG).show();
		}


	}


	@Override

	public int onStartCommand(Intent intent, int flags, int startId){
		// START YOUR TASKS
		clientManager = new AmazonClientManager();
		local_user_information =  this.getSharedPreferences(PREFS_NAME,0);

		//PRIMARY_PHONE_NUMBER = local_user_information.getString("primaryPhoneNumber", "defalut");
		PHONE_NUMBER = local_user_information.getString("PhoneNumber", "default");

		/*if (PRIMARY_PHONE_NUMBER.equals(PHONE_NUMBER)){*/

		Toast.makeText(this , "serice test start", Toast.LENGTH_SHORT).show();
		broadcastReceiver = new BroadcastReceiver() {
			@Override
			public void onReceive(Context ctx, Intent intent)
			{

				if (intent.getAction().compareTo(Intent.ACTION_TIME_TICK) == 0){
					ONLINE = local_user_information.getString("online_offline", "online");
					if (ONLINE.equals("online")){
						Toast.makeText(getBaseContext(), "updateOnlineStatus ", Toast.LENGTH_LONG).show();
						if (MyInfoActivity.make_me_available_switch == null){
							Toast.makeText(getBaseContext(), "background update", Toast.LENGTH_LONG).show();
							updateOnlineStatus();
						}
						else{
							if (MyInfoActivity.make_me_available_switch.isEnabled()){
								Toast.makeText(getBaseContext(), "foreground update", Toast.LENGTH_LONG).show();
								updateOnlineStatus();
								updateOnlineSwitchDisplay();
							}
							else{
								Toast.makeText(getBaseContext(), "foreground not update", Toast.LENGTH_LONG).show();
							}
						}

					}

					//updateFromDateDisplay();

					//updateOnlineStatus();

				}

			}
		};

		registerReceiver(broadcastReceiver, new IntentFilter(Intent.ACTION_TIME_TICK));
		/*}*/
		return super.onStartCommand(intent, flags, startId);
	}

	@Override
	public void onDestroy() {
		// STOP YOUR TASKS


		Toast.makeText(this, "service test stop", Toast.LENGTH_SHORT).show();

		super.onDestroy();
	}


	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return null;
	}


	private void updateStartTime(){
		PHONE_NUMBER = local_user_information.getString("PhoneNumber", "default");

		new Thread(new Runnable(){

			@Override
			public void run() {
				// TODO Auto-generated method stub
				SimpleDB.updateSingleAttribute(clientManager, PHONE_NUMBER,SimpleDB.AVAILABILITY_ITEM, SimpleDB.START_TIME_ATTRIBUTE, START_TIME);

			}

		}).start();

	}


	private void updateEndTime(){
		PHONE_NUMBER = local_user_information.getString("PhoneNumber", "default");



		// TODO Auto-generated method stub
		new Thread(new Runnable(){

			@Override
			public void run() {
				// TODO Auto-generated method stub

				SimpleDB.updateSingleAttribute(clientManager, PHONE_NUMBER,SimpleDB.AVAILABILITY_ITEM, SimpleDB.END_TIME_ATTRIBUTE, END_TIME);
			}

		}).start();



	}

	private void updateDataBaseForOnlineStatus(final boolean isChecked){
		//PRIMARY_PHONE_NUMBER = local_user_information.getString("primaryPhoneNumber", "defalut");
		//PRIMARY_NICKNAME = local_user_information.getString("primaryNickname", "default");
		PHONE_NUMBER = local_user_information.getString("PhoneNumber", "default");
		NICKNAME = local_user_information.getString("Nickname", "default");

		if (MyInfoActivity.make_me_available_switch != null){
			MyInfoActivity.make_me_available_switch.setEnabled(false);
		}

		local_user_editor = local_user_information.edit();

		// TODO Auto-generated method stub
		new Thread(new Runnable(){

			@Override
			public void run() {
				// TODO Auto-generated method stub
				if (isChecked){
					local_user_editor = local_user_information.edit();
					local_user_editor.putString("online_offline", "online");
					local_user_editor.commit();



					SimpleDB.updateSingleAttribute(clientManager, PHONE_NUMBER, SimpleDB.ONLINE_ITEM, SimpleDB.ONLINE_ATTRIBUTE, "online");

					HashMap<String,String> myFriendList = SimpleDB.getAttributesForItem(clientManager, PHONE_NUMBER, SimpleDB.FRIEND_LIST_ITEM);

					myFriendList.remove("2060000000");
					myFriendList.remove("Name");

					String [] myFriendNumberList =  myFriendList.keySet().toArray(new String[0]);		

					HashMap<String, String> beUnavailableToFriendsList = SimpleDB.getAttributesForItem(clientManager, PHONE_NUMBER, SimpleDB.BE_UNAVAILABLE_TO_LIST_ITEM);





					for (int i = 0; i < myFriendNumberList.length; i++){

						if (!beUnavailableToFriendsList.containsKey(myFriendNumberList[i])){
							HashMap<String, String> onlineFriendList = SimpleDB.getAttributesForItem(clientManager,myFriendNumberList[i], SimpleDB.ONLINE_FRIEND_LIST_ITEM);
							onlineFriendList.put(PHONE_NUMBER,NICKNAME);
							SimpleDB.deleteItem(clientManager, myFriendNumberList[i], SimpleDB.ONLINE_FRIEND_LIST_ITEM);
							SimpleDB.updateAttributesForItem(clientManager, myFriendNumberList[i], SimpleDB.ONLINE_FRIEND_LIST_ITEM, onlineFriendList);

							HashMap<String, String> offlineFriendList = SimpleDB.getAttributesForItem(clientManager,myFriendNumberList[i], SimpleDB.OFFLINE_FRIEND_LIST_ITEM);
							offlineFriendList.remove(PHONE_NUMBER);
							SimpleDB.deleteItem(clientManager, myFriendNumberList[i], SimpleDB.OFFLINE_FRIEND_LIST_ITEM);
							SimpleDB.updateAttributesForItem(clientManager, myFriendNumberList[i], SimpleDB.OFFLINE_FRIEND_LIST_ITEM, offlineFriendList);
						}
					}

					myFriendList.put("2060000000", "dummyUser");


					SimpleDB.deleteItem(clientManager, PHONE_NUMBER, SimpleDB.FRIEND_LIST_ITEM);

					SimpleDB.updateAttributesForItem(clientManager, PHONE_NUMBER, SimpleDB.FRIEND_LIST_ITEM, myFriendList);

					/*
					local_user_editor.putString("online", "online");
					local_user_editor.commit();*/

				}
				else{
					local_user_editor = local_user_information.edit();
					local_user_editor.putString("online_offline", "offline");
					local_user_editor.commit();



					SimpleDB.updateSingleAttribute(clientManager, PHONE_NUMBER, SimpleDB.ONLINE_ITEM, SimpleDB.ONLINE_ATTRIBUTE, "offline");



					HashMap<String,String> myFriendList = SimpleDB.getAttributesForItem(clientManager, PHONE_NUMBER, SimpleDB.FRIEND_LIST_ITEM);

					myFriendList.remove("2060000000");
					myFriendList.remove("Name");


					String [] myFriendNumberList =  myFriendList.keySet().toArray(new String[0]);		

					for (int i = 0; i < myFriendNumberList.length; i++){

						HashMap<String, String> onlineFriendList = SimpleDB.getAttributesForItem(clientManager,myFriendNumberList[i], SimpleDB.ONLINE_FRIEND_LIST_ITEM);
						onlineFriendList.remove(PHONE_NUMBER);
						SimpleDB.deleteItem(clientManager, myFriendNumberList[i], SimpleDB.ONLINE_FRIEND_LIST_ITEM);
						SimpleDB.updateAttributesForItem(clientManager, myFriendNumberList[i], SimpleDB.ONLINE_FRIEND_LIST_ITEM, onlineFriendList);

						HashMap<String, String> offlineFriendList = SimpleDB.getAttributesForItem(clientManager,myFriendNumberList[i], SimpleDB.OFFLINE_FRIEND_LIST_ITEM);
						offlineFriendList.put(PHONE_NUMBER, NICKNAME);
						SimpleDB.deleteItem(clientManager, myFriendNumberList[i], SimpleDB.OFFLINE_FRIEND_LIST_ITEM);
						SimpleDB.updateAttributesForItem(clientManager, myFriendNumberList[i], SimpleDB.OFFLINE_FRIEND_LIST_ITEM, offlineFriendList);
					}

					myFriendList.put("2060000000", "dummyUser");


					SimpleDB.deleteItem(clientManager, PHONE_NUMBER, SimpleDB.FRIEND_LIST_ITEM);

					SimpleDB.updateAttributesForItem(clientManager, PHONE_NUMBER, SimpleDB.FRIEND_LIST_ITEM, myFriendList);

					/*		local_user_editor.putString("online", "offline");
					local_user_editor.commit();*/
				}

				Message msg = Message.obtain();
				msg.what = 1;
				handler.sendMessage(msg);

			}

		}).start();
	}


	private void updateOnlineSwitchDisplay(){
		ONLINE = local_user_information.getString("online_offline", "default");
		if (ONLINE.equals("online")){
			MyInfoActivity.make_me_available_switch.setChecked(true);
		}
		else if (ONLINE.equals("offline")){
			MyInfoActivity.make_me_available_switch.setChecked(false);
		}
	}


}
